package st.business.tepth.business.user.busnumber.workholder.maintain.work.content.standardwork.partrecord;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.constraint.ConstraintLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.TextView;

import com.bigkoo.pickerview.builder.OptionsPickerBuilder;
import com.bigkoo.pickerview.listener.CustomListener;
import com.bigkoo.pickerview.listener.OnOptionsSelectListener;
import com.bigkoo.pickerview.view.OptionsPickerView;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemChildClickListener;

import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

import butterknife.BindView;
import butterknife.OnClick;
import st.business.tepth.R;
import st.business.tepth.R2;
import st.business.tepth.base.OnItemChooseListener;
import st.business.tepth.business.bean.MaintainWorkDetailBean;
import st.business.tepth.business.bean.OperationBean;
import st.business.tepth.business.bean.PartBean;
import st.business.tepth.business.bean.PartLocationBean;
import st.business.tepth.business.bean.PersonBean;
import st.business.tepth.business.bean.PickNumberBean;
import st.business.tepth.business.bean.ProgramBean;
import st.business.tepth.business.user.busnumber.workholder.dialog.DialogActionChoose;
import st.business.tepth.business.user.busnumber.workholder.dialog.DialogPartChoose;
import st.business.tepth.business.user.busnumber.workholder.dialog.DialogPartLocationChoose;
import st.business.tepth.business.user.busnumber.workholder.repair.work.content.RepairDataConvert;
import st.business.tepth.config.ItemFields;
import st.business.tepth.manager.GlobalDataManager;
import st.business.tepth.manager.UserManager;
import st.shadow.library.core.base.mvp.MvpFragment;
import st.shadow.library.core.util.utilcode.util.ScreenUtils;
import st.shadow.library.core.util.utilcode.util.ToastUtils;
import st.shadow.library.ui.dialog.DialogLoader;
import st.shadow.library.ui.dialog.IDialogClickListener;
import st.shadow.library.ui.recycler.MultipleItemEntity;

import static st.business.tepth.business.user.busnumber.workholder.maintain.work.content.standardwork.partrecord.PartRecordAdapter.TYPE_UN_CONFIRM;

/**
 * Author: shadow
 * Email:  1025431817@qq.com
 * Time:   2019-07-01 14:50
 * 临时添加的零部件记录页面
 */

public class PartRecordDelegate extends MvpFragment<PartRecordPresenter> implements PartRecordContract.View {
    public static PartRecordDelegate newInstance(int repairId,
                                                 int repairTaskId,
                                                 int maintainId,
                                                 int status) {
        Bundle bundle = new Bundle();
        bundle.putInt("repairId", repairId);
        bundle.putInt("status", status);
        bundle.putInt("repairTaskId", repairTaskId);
        bundle.putInt("maintainId", maintainId);
        PartRecordDelegate delegate = new PartRecordDelegate();
        delegate.setArguments(bundle);
        return delegate;
    }

    @BindView(R2.id.tv_tile)
    TextView mTvTitle;
    @BindView(R2.id.tv_right_button)
    TextView mTvRightBtn;
    @BindView(R2.id.recycler_view)
    RecyclerView mRecyclerView;
    @BindView(R2.id.tv_bus_number)
    TextView mTvBusNumber;
    @BindView(R2.id.tv_work_type)
    TextView mTvBusType;
    @BindView(R2.id.layout_container)
    ConstraintLayout mLayoutContainer;
    @BindView(R2.id.tv_confirm)
    TextView mTvConfirm;

    private int mRepairId;
    private int mRepairTaskId;
    private int mMaintainId;
    private int mStatus;
    private OptionsPickerView pvCustomOptions;
    private PartRecordAdapter mPartRecordAdapter;
    private DialogLoader mDialogLoader;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Bundle bundle = getArguments();
        if (bundle != null) {
            mRepairId = bundle.getInt("repairId");
            mRepairTaskId = bundle.getInt("repairTaskId");
            mMaintainId = bundle.getInt("maintainId");
            mStatus = bundle.getInt("status");
        }
    }

    @Override
    public PartRecordPresenter getPresenter() {
        return new PartRecordPresenter(this);
    }

    @Override
    public Object setLayout() {
        return R.layout.delegate_part_record;
    }

    @Override
    public void onBindView(@Nullable Bundle savedInstanceState, View rootView) {
        mTvTitle.setText("作业记录");
        mTvRightBtn.setText("添加附加作业");
        mRecyclerView.setLayoutManager(new LinearLayoutManager(_mActivity));
        mRecyclerView.setAdapter(mPartRecordAdapter =
                new PartRecordAdapter(null));
        mRecyclerView.addOnItemTouchListener(new OnItemChildClickListener() {
            @Override
            public void onSimpleItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                MultipleItemEntity entity = (MultipleItemEntity) adapter.getItem(position);
                if (entity != null) {
                    int type = entity.getItemType();
                    int id = view.getId();
                    if (id == R.id.tv_choose_action) {
                        //动作
                        chooseAction(adapter, view, position);
                    } else if (id == R.id.tv_apply_goods || id == R.id.tv_part_code) {
                        //零部件和编码
                        choosePart(adapter, view, position);
                    } else if (id == R.id.tv_goods_count) {
                        //零部件数量
                        choosePartCount(adapter, view, position);
                    } else if (id == R.id.tv_place) {
                        //位置
                        choosePartLocation(adapter, view, position);
                    } else if (id == R.id.tv_operation) {
                        //删除
                        if (type == TYPE_UN_CONFIRM) {
                            adapter.remove(position);
                        } else {
                            //接口删除
                            deleteProgram(adapter, view, position);
                        }
                    }
                }
            }
        });
        mPartRecordAdapter.setEmptyView(R.layout.view_search_empty
                , (ViewGroup) mRecyclerView.getParent());
        mDialogLoader = new DialogLoader(_mActivity);
        if (mStatus < 3) {
            mTvConfirm.setVisibility(View.VISIBLE);
            mTvRightBtn.setVisibility(View.VISIBLE);
        } else {
            mTvConfirm.setVisibility(View.INVISIBLE);
            mTvRightBtn.setVisibility(View.INVISIBLE);
        }
    }

    private void deleteProgram(final BaseQuickAdapter adapter, View view, final int position) {
        mDialogLoader.showWarning("删除方案?", "请确认", new IDialogClickListener() {
            @Override
            public void onClick() {
                MultipleItemEntity entity = (MultipleItemEntity) adapter.getItem(position);
                if (entity != null) {
                    ProgramBean programBean = entity.getField(ItemFields.ITEM_OBJ);
                    mPresenter.deleteProgram(UserManager.getInstance().getToken(),
                            mRepairId, programBean.getFault_diagnostic_id(),
                            programBean.getId(), position);
                }
            }
        });
    }

    private void choosePartLocation(final BaseQuickAdapter adapter, final View view, final int position) {
        new DialogPartLocationChoose(_mActivity,
                new DialogPartLocationChoose.OnLocationChooseListener() {

                    @Override
                    public void onChoose(PartLocationBean partLocationBean, String temp) {
                        if (temp.isEmpty()) {
                            //没有临时添加的位置
                            MultipleItemEntity entity = (MultipleItemEntity) adapter.getItem(position);
                            if (entity != null) {
                                ProgramBean programBean = entity.getField(ItemFields.ITEM_OBJ);
                                programBean.setPositionName(partLocationBean.getPositionName());
                                programBean.setPositionCode(partLocationBean.getPositionCode());
                                //diagnoseBean.setAction_name(operationBean.getAction_name());
                                // diagnoseBean.setMaintenance_action_id(operationBean.getId());
                                ((TextView) view).setText(partLocationBean.getPositionName());
                            }
                        } else {
                            //有临时添加的位置
                            mDialogLoader.showProgressDialog(false, "正在添加",
                                    "请稍候...");
                            mPresenter.addTempLocation(UserManager.getInstance().getToken(),
                                    position, partLocationBean, temp);

                        }

                    }
                }).measureSize().show();
    }

    private void choosePartCount(final BaseQuickAdapter adapter, final View view, final int position) {
        pvCustomOptions = new OptionsPickerBuilder(_mActivity,
                new OnOptionsSelectListener() {
                    @Override
                    public void onOptionsSelect(int options1, int option2, int options3, View v) {
                        //返回的分别是三个级别的选中位置
                        MultipleItemEntity entity = (MultipleItemEntity) adapter.getItem(position);
                        if (entity != null) {
                            ProgramBean programBean = entity.getField(ItemFields.ITEM_OBJ);
                            if (programBean != null) {
                                PartBean partBean = programBean.getPart();
                                if (partBean != null) {
                                    partBean.setVal(options1 + 1);
                                    ((TextView) view).setText(String.format(
                                            Locale.CHINA, "%d", options1 + 1));
                                }
                            }
                        }
                    }
                })
                .setLayoutRes(R.layout.dialog_number_select, new CustomListener() {
                    @Override
                    public void customLayout(View v) {
                        v.findViewById(R.id.iv_close).setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                pvCustomOptions.dismiss();
                            }
                        });
                        v.findViewById(R.id.tv_confirm).setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                pvCustomOptions.returnData();
                                pvCustomOptions.dismiss();
                            }
                        });
                    }
                })
                .isDialog(true)
                .setOutSideCancelable(false)
                .build();
        List<PickNumberBean> list = new ArrayList<>();
        for (int i = 1; i < 50; i++) {
            list.add(new PickNumberBean(i + ""));
        }
        //noinspection unchecked
        pvCustomOptions.setPicker(list);//添加数据
        pvCustomOptions.show();
    }

    private void choosePart(final BaseQuickAdapter adapter, final View view,
                            final int position) {
        DialogPartChoose dialogPartChoose = new DialogPartChoose(_mActivity, mRepairId,
                new OnItemChooseListener<PartBean>() {
                    @Override
                    public void onChoose(PartBean partBean) {
                        MultipleItemEntity entity = (MultipleItemEntity) adapter.getItem(position);
                        if (entity != null) {
                            ProgramBean diagnoseBean = entity.getField(ItemFields.ITEM_OBJ);
                            TextView tv = ((TextView) view);
                            diagnoseBean.setPart(partBean);
                            if (view.getId() == R.id.tv_apply_goods) {
                                //零件
                                tv.setText(partBean.getMaterial_name());
                                TextView tvCode = (TextView) adapter.getViewByPosition(mRecyclerView,
                                        position, R.id.tv_part_code);
                                if (tvCode != null) {
                                    tvCode.setText(partBean.getMaterial_no() == null ?
                                            "无" : partBean.getMaterial_no());
                                }
                            } else {
                                //编号
                                tv.setText(partBean.getMaterial_no());
                                TextView tvName = (TextView) adapter.getViewByPosition(mRecyclerView,
                                        position, R.id.tv_apply_goods);
                                if (tvName != null) {
                                    tvName.setText(partBean.getMaterial_name());
                                }
                            }
                            TextView tvUnit = (TextView) adapter.getViewByPosition(mRecyclerView,
                                    position, R.id.tv_unit);
                            if (tvUnit != null) {
                                tvUnit.setText(partBean.getUnit() == null ? "无" : partBean.getUnit());
                            }
                        }
                    }
                }, true);
        Window dialogWindow = dialogPartChoose.getWindow();
        if (dialogWindow != null) {
            WindowManager.LayoutParams lp = dialogWindow.getAttributes();
            lp.width = ScreenUtils.getScreenWidth() * 1000 / 1280; // 宽度
            lp.height = ScreenUtils.getScreenHeight() * 720 / 1024; // 高度
            dialogWindow.setGravity(Gravity.CENTER);
            dialogWindow.setAttributes(lp);
            dialogPartChoose.show();
        }
    }

    private void chooseAction(final BaseQuickAdapter adapter, final View view, final int position) {
        new DialogActionChoose(_mActivity, GlobalDataManager.getInstance().getOperationBeans(),
                new OnItemChooseListener<OperationBean>() {

                    @Override
                    public void onChoose(OperationBean operationBean) {
                        MultipleItemEntity entity = (MultipleItemEntity) adapter.getItem(position);
                        if (entity != null) {
                            ProgramBean diagnoseBean = entity.getField(ItemFields.ITEM_OBJ);
                            diagnoseBean.setAction_name(operationBean.getAction_name());
                            diagnoseBean.setMaintenance_action_id(operationBean.getId());
                            ((TextView) view).setText(operationBean.getAction_name());
                        }
                    }
                }).show();
    }

    @Override
    public void onLazyInitView(@Nullable Bundle savedInstanceState) {
        super.onLazyInitView(savedInstanceState);
        addTopView(R.layout.view_loading, mLayoutContainer);
        mPresenter.getDetailData(UserManager.getInstance().getToken(),
                mMaintainId);
    }

    @OnClick(R2.id.tv_back)
    public void onBack() {
        //pop();
        _mActivity.onBackPressed();
    }

    @OnClick(R2.id.tv_right_button)
    public void onRightClick() {
        new DialogActionChoose(_mActivity, GlobalDataManager.getInstance().getOperationBeans(),
                new OnItemChooseListener<OperationBean>() {

                    @Override
                    public void onChoose(OperationBean operationBean) {
                        ProgramBean programBean = new ProgramBean();
                        programBean.setAction_name(operationBean.getAction_name());
                        programBean.setMaintenance_action_id(operationBean.getId());
                        programBean.setMainPerson(new PersonBean(UserManager.getInstance()
                                .getCurrentUserName(),
                                UserManager.getInstance().getCurrentUserCode()));
                        MultipleItemEntity entity = MultipleItemEntity.builder()
                                .setItemType(TYPE_UN_CONFIRM)
                                .setField(ItemFields.ITEM_OBJ, programBean)
                                .setField("status", mStatus)
                                .build();
                        if (mPartRecordAdapter != null) {
                            mPartRecordAdapter.addData(0, entity);
                        }
                    }
                }).show();
    }

    @Override
    public void showData(MaintainWorkDetailBean workDetailBean) {
        if (mPartRecordAdapter != null && workDetailBean != null) {
            mPartRecordAdapter.setNewData(
                    PartRecordAdapter.
                            convertList(workDetailBean.getRepairDiagnosticList(), mStatus));
            if (mTvBusNumber != null) {
                mTvBusNumber.setText(String.format("车辆编号:%s",
                        workDetailBean.getBusNo()));
            }
            if (mTvBusType != null) {
                mTvBusType.setText(String.format("作业类型:%s",
                        getTypeStr(workDetailBean.getRepairType())));
            }
        }
        removeTopView(mLayoutContainer);
        mDialogLoader.clearDialog();
    }

    @Override
    public void showError(String msg) {
        mDialogLoader.stopProgressWithFailed("提交失败", msg);
    }

    @Override
    public void deleteProgram(final int position) {
        mDialogLoader.stopProgressWithSuccess("删除成功", null, new IDialogClickListener() {
            @Override
            public void onClick() {
                mDialogLoader.clearDialog();
                if (mPartRecordAdapter != null) {
                    mPartRecordAdapter.remove(position);
                }
            }
        });
    }

    @Override
    public void showTempLocation(PartLocationBean partLocationBean, int position) {
        mDialogLoader.clearDialog();
        MultipleItemEntity entity = mPartRecordAdapter.getItem(position);
        if (entity != null) {
            ProgramBean programBean = entity.getField(ItemFields.ITEM_OBJ);
            programBean.setPositionName(partLocationBean.getPositionName());
            programBean.setPositionCode(partLocationBean.getPositionCode());
            mPartRecordAdapter.notifyItemChanged(position);
        }
    }

    @OnClick(R2.id.tv_confirm)
    public void onCommitProgram() {
        if (mPartRecordAdapter != null &&
                mPartRecordAdapter.hasNotCommitData()) {
            mPresenter.confirmProgram(UserManager.getInstance().getToken(),
                    mRepairId, mRepairTaskId, mMaintainId,
                    new RepairDataConvert().programListToJson(mPartRecordAdapter.getData(),
                            mRepairId,
                            0, 2));
            mDialogLoader.showProgressDialog(false, "正在提交", "请稍候...");
        } else {
            ToastUtils.showShort("请先添加方案");
        }
    }

    private String getTypeStr(int type) {
        String typeStr = "";
        switch (type) {
            case 1:
                typeStr = "小修";
                break;
            case 2:
                typeStr = "一级保养";
                break;
            case 3:
                typeStr = "二级保养";
                break;
            case 4:
                typeStr = "三级保养";
                break;
            case 5:
                typeStr = "电池保养";
                break;
        }
        return typeStr;
    }
}